package com.superbytecode.common.wrapper;

import lombok.Getter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.util.StringValueResolver;

/**
 * All rights Reserved, Designed By www.super-bytecode.com
 *
 * @ProjectName: superbytecode-beacon
 * @Package: com.superbytecode.common.wrapper
 * @ClassName: SpringContextUtil
 * @Description: [Spring环境上下文工具]
 * <p> </p>
 * @Author: [Lance Ting]
 * @Date: 2023/11/21 15:25
 * @Version: V1.0
 * @Copyright: 2023 www.super-bytecode.com Inc. All rights reserved.
 * TODO: 注意,本文件Lance Ting所作,如果转载或使用请标明具体出处!
 **/
@Getter
@Component
public class SpringContextUtil implements ApplicationContextAware, EmbeddedValueResolverAware {
    // -----------------------------------------------
    private static ApplicationContext applicationContext;
    private static StringValueResolver stringValueResolver;
    // -----------------------------------------------

    /**
     * 通过class获取bean
     * <p>
     * 获取实例，如果找不到会报错
     *
     * @param clazz class
     * @param <T>   返回的类型
     * @return Bean
     */
    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    public static <T> T getBean(String beanName, Class<T> clazz) {
        return applicationContext.getBean(beanName, clazz);
    }

    /**
     * 获取spring value，和@Value的效果相同
     * 注意：如果是获取配置，找不到配置会报异常
     *
     * @param spEL spring表达式，须用"${spEL}"括起来，否则返回值和入参相同
     * @return 表达式的值
     */
    public static String getContextValue(String spEL) {
        return stringValueResolver.resolveStringValue(spEL);
    }

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    @Override
    public void setEmbeddedValueResolver(@NonNull StringValueResolver resolver) {
        SpringContextUtil.stringValueResolver = resolver;
    }

}